//
//  XZCurrencyController.m
//  生活小助手
//
//  Created by lixiangzhou on 14-8-7.
//  Copyright (c) 2014年 lxz. All rights reserved.
//

#import "XZCurrencyController.h"
#import "XZFunctionKey.h"
#import "XZHttpTool.h"
#import "MBProgressHUD+MJ.h"
#import "MJExtension.h"
#import "DwtExchangeRmbquotData.h"
#import "DwtExchangeFrateData.h"
#import "DwtExchangeRmbquotCell.h"
#import "DwtExchangeFrateCell.h"
#import "AFHTTPRequestOperationManager.h"
#import "AFHTTPSessionManager.h"
#import "MBProgressHUD+MJ.h"

@interface XZCurrencyController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) UISegmentedControl *segementControl;
@property (strong, nonatomic) UITableView *exchangeRmbquotView;
@property (nonatomic,strong)NSMutableArray *rmbquotDataes;
@property (nonatomic,strong)NSMutableArray *frateDataes;
@property (nonatomic,assign,getter = isRmbuotShow)BOOL rmbuotShow;
@end

@implementation XZCurrencyController

-(NSMutableArray *)rmbquotDataes{
    if (_rmbquotDataes==nil) {
        _rmbquotDataes = [NSMutableArray array];
    }
    return _rmbquotDataes;
}

-(NSMutableArray *)frateDataes{
    if (_frateDataes==nil) {
        _frateDataes = [NSMutableArray array];
    }
    return _frateDataes;
}

-(UITableView *)exchangeRmbquotView{
    if (_exchangeRmbquotView==nil) {
        _exchangeRmbquotView = [[UITableView alloc]initWithFrame:CGRectMake(0,95, 320, 480-60) style:UITableViewStyleGrouped];
        _exchangeRmbquotView.delegate= self ;
        _exchangeRmbquotView.dataSource = self;
        _exchangeRmbquotView.sectionHeaderHeight = 35;
//        _exchangeRmbquotView.rowHeight = 189;
        _exchangeRmbquotView.bounces=NO;
        _exchangeRmbquotView.contentInset=UIEdgeInsetsMake(-35, 0, 0, 0);

    }
    return _exchangeRmbquotView;
}

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    
    
    self.title = @"货币汇率";
    self.rmbuotShow=YES;
    self.view.backgroundColor = kGlobalBackgroundColor;
    
    
    [self addViews];

    /*************监控网络状态*****************/
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *mgr=[AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
                
            case AFNetworkReachabilityStatusNotReachable:
                [MBProgressHUD showError:@"请链接网络"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [MBProgressHUD hideHUD];
                });
                break;
                
        }
    }];
    
    
    
    /****************人民币牌价***********************/
    NSString *strUrl=[NSString stringWithFormat:@"http://web.juhe.cn:8080/finance/exchange/rmbquot?key=b584fdc061e567c38eb17bccf49f5121&dtype=json"];
    NSURL *url=[NSURL URLWithString:strUrl];
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    
    NSURLResponse *response=[[NSURLResponse alloc]init];
    NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    if(data==nil){
        [MBProgressHUD showError:@"请检查网络"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
        });
        return;
    }
    
    NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    
    NSDictionary *dictDataes = [[dict objectForKey:@"result"] lastObject];
    NSArray *dataKeyes = [dictDataes allKeys];
    for (NSString *dataKey in dataKeyes) {
        NSDictionary *dictData = dictDataes[dataKey];
        DwtExchangeRmbquotData *exchangeRmbquotData = [DwtExchangeRmbquotData exchangeRmbquotDataWithDictionary:dictData];
        [self.rmbquotDataes addObject:exchangeRmbquotData];
    }
/******************外汇汇率**************************/
    NSString *strUrlFrate=[NSString stringWithFormat:@"http://web.juhe.cn:8080/finance/exchange/frate?key=b584fdc061e567c38eb17bccf49f5121&dtype=json"];
    NSURL *urlFrate=[NSURL URLWithString:strUrlFrate];
    NSURLRequest *requestFrate=[NSURLRequest requestWithURL:urlFrate];
    
    NSURLResponse *responseFrate=[[NSURLResponse alloc]init];
    NSData *dataFrate=[NSURLConnection sendSynchronousRequest:requestFrate returningResponse:&responseFrate error:nil];
    
    if(dataFrate==nil){
        [MBProgressHUD showError:@"请检查网络"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
        });
        return;
    }
    
    
    NSDictionary *dictFrate=[NSJSONSerialization JSONObjectWithData:dataFrate options:NSJSONReadingMutableLeaves error:nil];
    
    NSDictionary *dictDataesFrate = [[dictFrate objectForKey:@"result"] lastObject];
    NSArray *dataKeyesFrate = [dictDataesFrate allKeys];
    for (NSString *dataKey in dataKeyesFrate) {
        NSDictionary *dictData = dictDataesFrate[dataKey];
        DwtExchangeFrateData *exchangeFrateData = [DwtExchangeFrateData exchangeFrateDataWithDictionary:dictData];
        [self.frateDataes addObject:exchangeFrateData];
    }

}
- (void)addViews
{
    UISegmentedControl *segementControl = [[UISegmentedControl alloc] initWithItems:@[@"人民币牌价", @"外汇汇率"]];
    segementControl.y = CGRectGetMaxY(self.navigationController.navigationBar.frame);
    segementControl.width = self.view.width;
    [segementControl addTarget:self action:@selector(changeValue:) forControlEvents:UIControlEventValueChanged];
    self.segementControl = segementControl;
    [self.view addSubview:segementControl];
    
    segementControl.selectedSegmentIndex = 0;
    
    [self.view addSubview:self.exchangeRmbquotView];
}
- (void)changeValue:(UISegmentedControl *)segementControl
{
    self.rmbuotShow=!self.rmbuotShow;
    [self.exchangeRmbquotView reloadData];
    NSLog(@"%d", segementControl.selectedSegmentIndex);
}

#pragma tableDataSource 代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.isRmbuotShow) {
        return self.rmbquotDataes.count;
    }
    return self.frateDataes.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isRmbuotShow) {
        DwtExchangeRmbquotData *exchangeRmbquotData = self.rmbquotDataes[indexPath.row];
        DwtExchangeRmbquotCell *cell = [DwtExchangeRmbquotCell exchangeRmbquotCell];
        cell.exchangeRmbquotData=exchangeRmbquotData;
        
        
        return cell;
    }

    DwtExchangeFrateData *exchangeFrateData = self.frateDataes[indexPath.row];
    DwtExchangeFrateCell *cell = [DwtExchangeFrateCell exchangeFrateCell];
    cell.exchangeFrateData = exchangeFrateData;
    return cell;

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isRmbuotShow) {
        return 189;
    }
    return 249;
}
@end
